var Post = require('../lib/mongo').Post;
var marked = require('marked');

// 将 post 的 content 从 markdown 转换成 html
Post.plugin('contentToHtml', {
    afterFind: function (posts) {
      return posts.map(function (post) {
        post.content = marked(post.content);
        return post;
      });
    },
    afterFindOne: function (post) {
      if (post) {
        post.content = marked(post.content);
      }
      return post;
    }
  });
module.exports = {
  // 创建一篇文章
  create: function create(post) {
    return Post.create(post).exec();
  },


  // 通过文章 id 获取一篇文章
  getPostById: function getPostById(postId) {
    return Post
      .findOne({ _id: postId })
      .populate({ path: 'author', model: 'User' })
      .contentToHtml()
      .exec();
  },

  // 按创建时间降序获取所有用户文章或者某个特定用户的所有文章
  getPosts: function getPosts(author) {
    var query = {};
    if (author) {
      query.author = author;
    }
    return Post
      .find(query)
      .sort({ _id: -1 })
      .populate({ path: 'author', model: 'User' })
      .contentToHtml()
      .exec();
  },


  updatePostById: function updatePostById(postId, author, data){
     return Post
            .update({ author: author, _id: postId }, { $set: data })
            .exec(); 
  },

  delPostById: function delPostById(postId, author){
     return Post
            .remove({ author: author, _id: postId})
            .exec(); 
  }
};